<template>
  <div>
    <div id="breadcrumb">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <router-link to="/admin">管理员列表</router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>{{ this.$route.params.id > 0 ? '编辑' : '新增' }}</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <a-card :bordered="false">
      <template>
        <a-form :form="form" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }" @submit="handleSubmit">
          <a-form-item label="用户名">
            <a-input
                v-decorator="['name', { rules: [{ required: true, message: '请输入用户名' }] }]"
                allowClear
            />
          </a-form-item>
          <a-divider dashed/>
          <a-form-item label="昵称">
            <a-input
                v-decorator="['username', { rules: [{ required: true, message: '请输入昵称' }] }]"
                allowClear
            />
          </a-form-item>
          <a-divider dashed/>
          <a-form-item label="角色">
            <a-select
                v-decorator="['role_id',{ rules: [{ required: true, message: '请配置角色' }] },]"
                placeholder="请选择角色"
                allowClear
                :options="roles"
            />
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 12, offset: 8 }">
            <a-button type="primary" html-type="submit">
              保存
            </a-button>
          </a-form-item>
        </a-form>
      </template>
    </a-card>
  </div>
</template>

<script>
export default {
  name: 'AdminEdit',
  data () {
    return {
      form: null,
      roles: []
    }
  },
  mounted () {
    if (this.$route.params.id > 0) {
      this.first()
    }
    this.form = this.$form.createForm(this)
    this.fetchRoles()
  },
  methods: {
    handleSubmit: function() {
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.$confirm({
            title: '确认操作',
            content: '保存后将无法撤回',
            onOk: () => this.$http.post(`api/admin/users?id=${this.$route.params.id}`,
                values).then((result) => {
              this.$message.success('编辑成功')
            }, (error) => {
              this.$message.error(error.message)
            })
          })
        }
      })
    },
    fetchRoles () {
      this.$http.get('api/admin/search/roles').then((result) => {
        const data = []

        result.forEach((item) => {
          data.push({
            label: item.name,
            key: item.id
          })
        })
        this.roles = data
      })
    },
    first () {
      this.$http.get(`api/admin/users/${this.$route.params.id}`).then((result) => {
        this.form.setFieldsValue({
          name: result.name,
          username: result.username,
          role_id: result.role_id
        })
      })
    }
  }
}
</script>

<style scoped>
#breadcrumb {
  margin-top: 0;
  margin-bottom: 10px;
}
</style>